package com.wxxymaker.edu.controller.api;

import com.blade.ioc.annotation.Inject;
import com.blade.kit.CollectionKit;
import com.blade.kit.StringKit;
import com.blade.mvc.Const;
import com.blade.mvc.annotation.Param;
import com.blade.mvc.annotation.Path;
import com.blade.mvc.annotation.PostRoute;
import com.blade.mvc.annotation.Route;
import com.blade.mvc.http.ByteBody;
import com.blade.mvc.http.Response;
import com.blade.mvc.ui.RestResponse;
import com.wxxymaker.edu.model.entity.CountInfo;
import com.wxxymaker.edu.model.entity.SysRecord;
import com.wxxymaker.edu.model.entity.User;
import com.wxxymaker.edu.service.*;
import com.wxxymaker.edu.utils.FileUtils;
import com.wxxymaker.edu.utils.TimeUtils;
import io.github.biezhi.anima.page.Page;
import io.github.biezhi.excel.plus.ExcelPlus;

import java.io.File;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @AUTHOR soft
 * @DATE 2019/3/11 20:56
 * @DESCRIBE 系统一些数据的统计接口 都是新加的
 */
@Path(restful = true, value = "/count/api")
public class SysCountApi {

    @Inject
    private NoteService noteService;

    @Inject
    private CommentService commentService;

    @Inject
    private MaterialService materialService;

    @Inject
    private PracticeService practiceService;

    @Inject
    private SysCountService countService;

    @Inject
    private SysRecordService recordService;

    @PostRoute("/views") // 查询历史访客
    public RestResponse views(@Param int page, @Param int limit) {
        Page<SysRecord> recordPage = recordService.getPage(page, limit);
        if (CollectionKit.isNotEmpty(recordPage.getRows())) {
            return RestResponse.ok(recordPage);
        }
        return RestResponse.fail();
    }

    /**
     * 指定课程的所有数据的个数
     *
     * @param kid 课程id
     * @return 个数json对象
     */
    @PostRoute("/course/numbers")
    public RestResponse numbers(@Param Integer kid) {
        long notes = noteService.countBykId(kid);
        long comments = commentService.countBykId(kid);
        long mates = materialService.countBykId(kid, "0"); // 课外资料
        long practices = practiceService.countBykId(kid);

        Map<String, Long> result = new LinkedHashMap<>();
        result.put("note", notes);
        result.put("comment", comments);
        result.put("material", mates);
        result.put("practice", practices);
        return RestResponse.ok(result);
    }

    /**
     * 系统统计 计算所有数据
     *
     * @return 统计数据
     */
    @PostRoute("/data")
    public RestResponse data(@Param(defaultValue = "1") Integer page,
                             @Param(defaultValue = "10") Integer limit,
                             User user) {
        Page<CountInfo> infoPage = countService.page(page, limit, user);

        if (infoPage != null) {
            return RestResponse.ok(infoPage);
        }
        return RestResponse.fail();
    }

    @Route("/excel")
    public void excel(@Param String role, Response response) throws Exception {
        User user = new User();
        try {
            user.setRole(Integer.valueOf(role));
        } catch (Exception ignored) {}
        Page<CountInfo> page = countService.page(1, Integer.MAX_VALUE, user);
        if (page != null) {
            ExcelPlus plus = new ExcelPlus();
            File file = new File(Const.CLASSPATH, "temp.xls");
            if (file.exists()) {
                file.delete();
            }
            FileUtils.createFile(file);
            if (role.equals("1")) {
                List<CountInfo.Student> students = page.getRows().stream().map(CountInfo::toStudent).collect(Collectors.toList());
                plus.export(students).writeAsFile(file);
            } else {
                plus.export(page.getRows()).writeAsFile(file);
            }

            String filename = "stat-" + TimeUtils.getDate() + ".xls";
            response.header("Content-Disposition", "attachment; filename=" + filename)
                    .header("Content-Length", String.valueOf(file.length()))
                    .contentType(StringKit.mimeType(filename));
            response.body(ByteBody.of(file));
        } else {
            response.json("no data");
        }
    }
}
